<?php

namespace App\Http\Requests;

use App\Enum\Models\System\Admin\Status;
use App\Models\System\Admin;
use Illuminate\Auth\Events\Lockout;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;

class LoginRequest extends FormRequest
{
    /**
     * 不需要登录
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * 验证规则
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        $rules = [
            'username' => 'required',
            'password' => 'required',
        ];
        // 根据配置来验证是否需要验证码
        if (config('admin.login_captcha')) {
            $rules['captchakey'] = 'required';
            $rules['captcha'] = 'required|captcha_api:'.$this->captchakey;
        }

        return $rules;
    }

    public function attributes(): array
    {
        return [
            'username' => __('admin.username'),
            'password' => __('admin.password'),
            'captchakey' => __('admin.captchakey'),
            'captcha' => __('admin.captcha'),
        ];
    }

    /** 验证通过 */
    public function validateUser(): Admin
    {
        $this->ensureIsNotRateLimited();

        /** @var Admin */
        $admin = Admin::query()->where('username', $this->username)->first();
        if (! $admin || ! Hash::check($this->password, $admin->password)) {

            RateLimiter::hit($this->throttleKey());

            throw ValidationException::withMessages([
                'username' => __('auth.failed'),
            ]);
        }

        /**
         * 状态
         */
        if ($admin->status != Status::Normal->value) {

            RateLimiter::hit($this->throttleKey());

            throw ValidationException::withMessages([
                'username' => __('auth.status.disabled'),
            ]);
        }

        RateLimiter::clear($this->throttleKey());

        return $admin;
    }

    /**
     * 判断是否限流
     */
    public function ensureIsNotRateLimited(): void
    {
        if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) {
            return;
        }

        event(new Lockout($this));

        $seconds = RateLimiter::availableIn($this->throttleKey());

        throw ValidationException::withMessages([
            'email' => trans('auth.throttle', [
                'seconds' => $seconds,
                'minutes' => ceil($seconds / 60),
            ]),
        ]);
    }

    /** 限流器键名 */
    public function throttleKey(): string
    {
        return Str::transliterate(Str::lower($this->input('username')).'|'.$this->ip());
    }
}
